package bc.swim2.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.naming.Context;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bc.swim2.ejb.entity.RegisteredUser;
import bc.swim2.ejb.session.UserManagerBeanRemote;

/**
 * Servlet implementation class SearchUsersServlet
 */
public class SearchUsersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SearchUsersServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("methodName").equals("searchUsers")) {
			searchUsers(request, response);
		}
	}

	private void searchUsers(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			String pattern = request.getParameter("pattern");

			List<RegisteredUser> users = null;

			Object ref2 = ctx.lookup("UserManagerBean/remote");
			UserManagerBeanRemote um = (UserManagerBeanRemote) ref2;

			users = um.getUsersByPattern(pattern);
			session.setAttribute("userListTmp1", users);

			response.sendRedirect("MainServlet?to=SearchHelpAndUsersResult");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}